package com.navercorp.utilset.system;

import com.navercorp.utilset.utils.UtilSetLogUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Function description
 * class RootChecker
 */
public class RootChecker {
    private static final String TAG = RootChecker.class.getName();

    private static final String[] PLACES = {
        "/sbin/", "/system/bin/", "/system/xbin/", "/data/local/xbin/", "/data/local/bin/", "/system/sd/xbin/",
        "/system/bin/failsafe/", "/data/local/"
    };

    /**
     * isRootAvailable
     *
     * @return true or false
     */
    public boolean isRootAvailable() {
        for (String where : PLACES) {
            if (hasFile(where)) {
                return true;
            }
        }
        return false;
    }

    private boolean hasFile(String fullPath) {
        try {
            File file = new File(fullPath);
            return file.exists();
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * checkRootingDevice
     *
     * @return true or false
     */
    public boolean checkRootingDevice() {
        boolean isRootingFlag = false;
        BufferedReader reader = null;
        try {
            Process process = Runtime.getRuntime().exec("find /data");

            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            String result = reader.readLine();
            if (result == null) {
                UtilSetLogUtils.error(TAG, "Failed to execute find command");
            }

            if (result.contains("/data")) {
                isRootingFlag = true;
            }
        } catch (Exception e) {
            isRootingFlag = false;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    UtilSetLogUtils.error(TAG, "Error occurred while closing input stream");
                }
            }
        }

        if (!isRootingFlag) {
            isRootingFlag = checkRootingFiles(PLACES);
        }

        return isRootingFlag;
    }

    private boolean checkRootingFiles(String[] filePaths) {
        boolean isResult = false;
        File file;

        for (String path : filePaths) {
            file = new File(path);

            if (file != null && file.exists() && file.isFile()) {
                isResult = true;
                break;
            } else {
                isResult = false;
            }
        }
        return isResult;
    }
}
